package com.chchwk.gaodelivelocation;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class AMapActivity extends AppCompatActivity implements LocationSource {
    public static final String TAG = AMapActivity.class.getSimpleName();
    @InjectView(R.id.map)
    MapView mMapView;
    @InjectView(R.id.btn_standard_map)
    Button mBtnStandardMap;
    @InjectView(R.id.btn_satellite_map)
    Button mBtnSatelliteMap;
    @InjectView(R.id.btn_screen)
    Button mBtnScreen;
    @InjectView(R.id.btn_auto_zoom)
    Button mBtnAutoZoom;
    @InjectView(R.id.ivScreen)
    ImageView ivScreen;
    @InjectView(R.id.ivScreen1)
    ImageView ivScreen1;
    private AMap mMap;
    private UiSettings mUiSettings;
    private static final String LATITUDE = "latitude";
    private static final String LONGITUDE = "longitude";
    private static final String LATLNG = "latlng";
    private static final String ZOOM = "zoom";
    private List<Map<String, Object>> mLatLngList;
    private List<Marker> mMarkers;
    private int mZoom;
    private Bitmap mBitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amap);
        ButterKnife.inject(this);
        //定义了一个地图view
        mMapView = (MapView) findViewById(R.id.map);
        mMapView.onCreate(savedInstanceState);// 此方法必须重写
        //初始化地图变量
        if (mMap == null) {
            mMap = mMapView.getMap();
            mUiSettings = mMap.getUiSettings();
            initUiSettings();
        }
        // 1.获取网络数据
        initData();
        // 2.获取中心点和缩放级别
        Map cenPointAndZoom = getCenterPoint(mLatLngList);
        LatLng cenPoint = (LatLng) cenPointAndZoom.get(LATLNG);
        mZoom = (int) cenPointAndZoom.get(ZOOM);
        // 3.设置中心点
        moveCameraToCenter(cenPoint, mZoom);
        // 4.添加点标记
        addMarkers();
        // 5.显示所有的标记信息
//        showMarkerInfoWindow();

    }

    private void showMarkerInfoWindow() {
        for (int i = 0; i < mMarkers.size(); i++) {
            Marker mMarker = mMarkers.get(i);
            if (mMarker.isInfoWindowShown()) {
                mMarker.hideInfoWindow();
            } else {
                mMarker.showInfoWindow();
            }
        }
    }

    private void addMarkers() {
        for (int i = 0; i < mLatLngList.size(); i++) {
            Map<String, Object> map = mLatLngList.get(i);
            double latitude = (double) map.get(LATITUDE);
            double longitude = (double) map.get(LONGITUDE);
            Marker mark = addMarker(new LatLng(latitude, longitude), "title" + i, "snippet" + i,
                    BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
            mMarkers.add(mark);
        }
    }

    private void initData() {
        mMarkers = new ArrayList<>();
        mLatLngList = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put(LATITUDE, 36.288455);
        map1.put(LONGITUDE, 120.403304);
        mLatLngList.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put(LATITUDE, 36.288023);
        map2.put(LONGITUDE, 120.403101);
        mLatLngList.add(map2);
        Map<String, Object> map3 = new HashMap<>();
        map3.put(LATITUDE, 36.287917);
        map3.put(LONGITUDE, 120.403414);
        mLatLngList.add(map3);
        Map<String, Object> map4 = new HashMap<>();
        map4.put(LATITUDE, 36.287798);
        map4.put(LONGITUDE, 120.403442);
        mLatLngList.add(map4);
        Map<String, Object> map5 = new HashMap<>();
        map5.put(LATITUDE, 36.287229);
        map5.put(LONGITUDE, 120.403378);
        mLatLngList.add(map5);

    }

    /**
     * 计算缩放级别
     *
     * @param maxLng
     * @param minLng
     * @param maxLat
     * @param minLat
     * @return
     */
    private int getZoom(double maxLng, double minLng, double maxLat, double minLat) {
        int zoom = 18;//默认级别
        int[] zoomArr = new int[]{10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000,
                20000, 30000, 50000, 100000, 200000, 500000, 1000000};//级别20到3。
        LatLng minPoint = new LatLng(minLat, minLng);  // 创建点坐标A
        LatLng maxPoint = new LatLng(maxLat, maxLng);  // 创建点坐标B
        float distance = AMapUtils.calculateLineDistance(minPoint, maxPoint);  //获取两点距离,保留小数点后两位
        Log.i(TAG, "distance: " + distance);
        for (int i = 0; i < zoomArr.length; i++) {
            if (zoomArr[i] > distance) {
                zoom = 20 - i + 3;//之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
                break;
            }
        }
        return zoom;
    }


    /**
     * 根据经纬度集合获取中心点
     *
     * @param latLngList
     */
    private Map getCenterPoint(List<Map<String, Object>> latLngList) {
        Map<String, Object> mMap = new HashMap<>();
        double minLat = (double) latLngList.get(0).get(LATITUDE);
        double maxLat = minLat;
        double minLng = (double) latLngList.get(0).get(LONGITUDE);
        double maxLng = minLng;
        for (int i = 0; i < latLngList.size(); i++) {
            Map<String, Object> map = latLngList.get(i);
            double latitude = (double) map.get(LATITUDE);
            double longitude = (double) map.get(LONGITUDE);
            if (latitude <= minLat) minLat = latitude;
            if (latitude >= maxLat) maxLat = latitude;
            if (longitude <= minLng) minLng = longitude;
            if (longitude >= maxLng) maxLng = longitude;
        }
        Log.i(TAG, "minLat: " + minLat + "maxLat: " + maxLat + "minLng: " + minLng + "maxLng: " + maxLng);
        int zoom = getZoom(maxLng, minLng, maxLat, minLat);
        double cenLat = (minLat + maxLat) / 2;
        double cenLng = (minLng + maxLng) / 2;
        Log.i(TAG, "cenLat: " + cenLat + "cenLng: " + cenLng + "zoom: " + zoom);
        mMap.put(ZOOM, zoom);
        mMap.put(LATLNG, new LatLng(cenLat, cenLng));
        return mMap;
    }


    /**
     * 在地图上添加坐标点
     *
     * @param mLatLng
     * @param title
     * @param snippet
     * @param icon
     */
    private Marker addMarker(LatLng mLatLng, String title, String snippet, Bitmap icon) {
        MarkerOptions mOptions = new MarkerOptions();
        mOptions.position(mLatLng)
                .title(title)
                .visible(true)
                .draggable(true)
                .snippet(snippet)
                .icon(BitmapDescriptorFactory.fromBitmap(icon));
        Marker mMarker = mMap.addMarker(mOptions);
//        mMarker.showInfoWindow();
        return mMarker;
    }

    /**
     * 设置中心点和地图缩放级别
     *
     * @param cenLatLng
     * @param zoom
     */
    private void moveCameraToCenter(LatLng cenLatLng, int zoom) {
        mMap.moveCamera(CameraUpdateFactory.changeLatLng(cenLatLng));
        mMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
    }


    private void initUiSettings() {
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setCompassEnabled(true);

        mMap.setLocationSource(this);// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(true); // 显示默认的定位按钮
        mMap.setMyLocationEnabled(true);// 可触发定位并显示定位层

        mUiSettings.setScaleControlsEnabled(true);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
        mMapView.onSaveInstanceState(outState);
    }

    @OnClick({R.id.btn_standard_map, R.id.btn_satellite_map, R.id.btn_screen, R.id.btn_auto_zoom, R.id.ivScreen})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_standard_map:
                mMap.setMapType(AMap.MAP_TYPE_NORMAL);
                break;
            case R.id.btn_satellite_map:
                mMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.btn_screen:
                ivScreen1.setVisibility(View.GONE);
                mapScreenShot();
                break;
            case R.id.btn_auto_zoom:
                mMap.moveCamera(CameraUpdateFactory.zoomTo(mZoom));
                break;
            case R.id.ivScreen:
                ivScreen1.setVisibility(View.VISIBLE);
                if (mBitmap != null) {
                    ivScreen1.setImageBitmap(mBitmap);
                } else {
                    ivScreen1.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
                }

                break;
        }
    }

    private void mapScreenShot() {
        mMap.getMapScreenShot(new AMap.OnMapScreenShotListener() {
            @Override
            public void onMapScreenShot(Bitmap bitmap) {
                if (null != bitmap) {
                    mBitmap = bitmap;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ivScreen.setImageBitmap(mBitmap);
                            Toast.makeText(AMapActivity.this, "图片更新完成", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    @Override
    public void activate(OnLocationChangedListener mOnLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

}
